package workgroup.osaka;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

/***************************************
 * アラーム時刻表時エリア
 ****************************************/
public class AlarmDigitalCalendar extends TextView {
    String TAG = "AlarmDigitalCalendar";
    final private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日");
    private Calendar m_cal;
    private boolean m_tickerStopped = false;
    private Handler m_handler;
    private Runnable m_ticker;
    
    // コンストラクタ
    public AlarmDigitalCalendar(Context context) {
        super(context);
        initClock(context);
    }
    
    public AlarmDigitalCalendar(Context context, AttributeSet attrs) {
        super(context, attrs);
        initClock(context);
    }
    
    // 初期化
    private void initClock(Context context) {
        if (m_cal == null) {
            m_cal = Calendar.getInstance();
        }
    }
    
    @Override
    protected void onAttachedToWindow() {
        m_tickerStopped = false;
        super.onAttachedToWindow();
        m_handler = new Handler();
        
        m_ticker = new Runnable() {
            public void run() {
                if (m_tickerStopped == true) return;
                m_cal.setTimeInMillis(System.currentTimeMillis());
                String day = convertDayOfWeek(m_cal);
                setText(day + "           " + sdf.format(m_cal.getTime()));
                invalidate();
                long oneDay = 24 * 60 * 60 * 1000;
                long now = SystemClock.uptimeMillis();
                TimeZone tz = TimeZone.getDefault();
                long next = now + (oneDay - ((System.currentTimeMillis() + tz.getRawOffset()) % oneDay));
                m_handler.postAtTime(m_ticker, next);
            }                
        };
        m_ticker.run();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        m_tickerStopped = true;
    }
    
    private String convertDayOfWeek(Calendar cal) {
        String dayOfWeek = "　　　　　　　"; 
        switch (cal.get(Calendar.DAY_OF_WEEK)) {
            case 1: dayOfWeek = "　　　　　　日"; break;
            case 2: dayOfWeek = "月　　　　　　"; break;
            case 3: dayOfWeek = "　火　　　　　"; break;
            case 4: dayOfWeek = "　　水　　　　"; break;
            case 5: dayOfWeek = "　　　木　　　"; break;
            case 6: dayOfWeek = "　　　　金　　"; break;
            case 7: dayOfWeek = "　　　　　土　"; break;
            default:
                // ここに入ってきたらおかしい
                Log.w(TAG, "曜日エラー: " + cal.get(Calendar.DAY_OF_WEEK));
                break;
        }
        return dayOfWeek;
    }
}